package com.dns.framework.dao;

import com.dns.framework.data.DatasetList;
import com.dns.framework.data.IData;
import com.dns.framework.data.IDataset;
import com.dns.framework.page.Pagination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 1、处理分页
 * @author :  yulei
 * @data :  2018/7/5 18:44
 * @Version :  1.0
 **/

public class DaoManager extends NamedParameterJdbcTemplate {

    protected Logger log = LoggerFactory.getLogger(getClass());

    public DaoManager(DataSource dataSource) {
        super(dataSource);
    }

    /**
     * 分页处理
     * @param sql
     * @param paramMap
     * @param pagination
     * @return
     * @throws DataAccessException
     */
    public IDataset queryForListByPage(String sql, Map<String,Object> paramMap, Pagination pagination)
            throws Exception {


            int count=getCount(sql,paramMap);
            sql=DaoHelper.getPagingSql(sql, paramMap,pagination.getStart(),pagination.getPageSize());

            List<Map<String,Object>> list= queryForList(sql, new MapSqlParameterSource(paramMap));
            log.debug("分页记录数:"+list.size());
            IDataset dataset =new DatasetList();
            dataset.setCount(count);
            dataset.setResultList(list);
            return dataset;

    }

    /**
     * 获取总记录数
     * @return
     * @throws Exception
     */
    private int getCount(String sql ,Map param) throws  Exception{

        List<Map<String ,String>> list=  queryForList(DaoHelper.getCountSql(sql),param);

        Map map =list.get(0);
        int count =Integer.parseInt(String.valueOf(map.get("CNT")));
        log.debug("记录总数:" +count);

        return  count;
    }

}
